package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取邮箱
        String phone = user.getPhone();
        //定义邮件验证码标题
        String subject = "测试";
        if(StringUtils.isNotEmpty(phone)){
            //生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //发送验证码
            String context = "欢迎测试,登录验证码为："+code+",五分钟内有效,请妥善保管!";

            //验证码缓存到redis中,有效时间为5min
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);

           //将验证码存入session
//            session.setAttribute(phone,code);

            //发送验证email
            userService.sendMsg(phone,subject,context);
            System.out.println("验证码为："+code);
            return R.success("发送成功");
        }



        return R.success("发送失败，请重试");
    }

    /*
        用户登录
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map,HttpSession session){
        //获取手机号和验证码
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        //从session中获取验证码
//        Object sessionAttribute = session.getAttribute(phone);

        //从redis中获取缓存的验证码
        Object codeInRedis = redisTemplate.opsForValue().get(phone);
        //比对二者验证码
        if(codeInRedis != null && codeInRedis.equals(code)){
            //比对上
            //判断是否为新用户
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            if(user == null){
                //新用户
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            //登陆成功,删除验证码缓存
            redisTemplate.delete(phone);
            return R.success(user);
        }
        return R.error("登录失败");
    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpServletRequest request){
        request.getSession().removeAttribute("userPhone");
        return R.success("已退出当前用户");
    }

}
